package com.waverider.promotion.web.bg.screen;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.ModelAndView;

import com.iacrqq.util.StringUtil;
import com.waverider.promotion.biz.manager.ShopManager;
import com.waverider.promotion.biz.util.TaoBaoUtils;
import com.waverider.promotion.constants.PromotionConstants;
import com.waverider.promotion.domain.ShopDO;
import com.waverider.promotion.web.AbstractController;
import com.waverider.promotion.web.LoginContext;

public class Login extends AbstractController {

	private ShopManager shopManager;

	@Override
	public ModelAndView handle(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		HttpSession session = request.getSession(true);

		ModelAndView modelAndView = null;
		Map<String, Object> context = null;

		// TOP parameters
		String topAppKey = request.getParameter(PromotionConstants.TOP_APPKEY);
		String topSessionKey = request
				.getParameter(PromotionConstants.TOP_SESSION);
		String topParameters = request
				.getParameter(PromotionConstants.TOP_PARAMETERS);

		// 参加校验
		if (StringUtil.isBlank(topAppKey) || StringUtil.isBlank(topSessionKey)
				|| StringUtil.isBlank(topParameters)) {
			modelAndView = new ModelAndView("bg/error");
			context = modelAndView.getModel();
			context.put("errorMsg", NOT_LOGIN_ERROR_MSG);
			return modelAndView;
		}

		Map<String, String> parametersMap = TaoBaoUtils
				.convertBase64StringtoMap(topParameters);
		Long vistorId = Long.valueOf(parametersMap
				.get(PromotionConstants.VISITOR_ID));
		String vistorNick = parametersMap.get(PromotionConstants.VISITOR_NICK);

		LoginContext loginContext = new LoginContext();
		loginContext.setIsLogin(true);
		loginContext.setSessionKey(topSessionKey);
		loginContext.setVistorId(vistorId);
		loginContext.setVistorNick(vistorNick);
		ShopDO shop = shopManager.syncShopInfoFromTaobao(topSessionKey,
				vistorId, vistorNick);
		loginContext.setShopId(shop.getShopId());
		session.setAttribute(LOGIN_CONTEXT, loginContext);
		loginContext.setUnfree(shopManager.isUnfree(vistorNick));
		return new ModelAndView("redirect:/bg/workspace.htm");
	}

	public void setShopManager(ShopManager shopManager) {
		this.shopManager = shopManager;
	}
}
